<?php
/**
 * DeletedBehavior class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright  Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

/**
 * Deleted behavior allows for "soft deleting" of records.
 */
class DeletedBehavior extends CActiveRecordBehavior
{
	/**
	 * Actions to be taken before calling find.
	 * @param CModelEvent $event the model event.
	 */
	public function beforeFind($event)
	{
		if ($this->owner->hasAttribute('deleted'))
		{
			$criteria = $this->owner->dbCriteria;
			
			if (strpos($criteria->condition, 't.deleted') === false)
			{
				$criteria->addCondition('t.deleted = 0');
				$this->owner->dbCriteria = $criteria;
			}
		}
	}

	/**
	 * Actions to be taken before calling delete.
	 * @param CModelEvent $event the model event.
	 */
	public function beforeDelete($event)
	{
		if ($this->owner->hasAttribute('deleted'))
		{
			$this->owner->deleted = 1;
			$this->owner->save(false);
			$event->isValid = false;
		}
	}
}